<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\GoodsModel;
use App\Services\Logger;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;

class GoodsDao extends BaseDao
{
    //获取构建builder
    public static function builder_query($params = []): Builder
    {
        $query = GoodsModel::query();

        $query->when(checkIsHasField($params,'goods_id'),function ($query)use ($params){
            $query->where('goods_id',$params['goods_id']);
        });
        $query->when(checkIsHasField($params,'category_id'),function ($query)use ($params){
            $query->where('category_id',$params['category_id']);
        });

        $query->when(checkIsHasField($params,'show'),function ($query)use ($params){
            $query->where('show',$params['show']);
        });

        $query->when(checkIsHasField($params,'shop_id'),function ($query)use ($params){
            $query->where('shop_id',$params['shop_id']);
        });


        return $query->orderByDesc('created_at');
    }
    public static function goods($params = []): LengthAwarePaginator
    {
        if(!checkIsHasField($params,'shop_id')){
            $params['shop_id'] = getShopId();
        }
        return self::builder_query($params)->paginate();
    }

    /**
     * @throws SysExceptions
     */
    public static function add(array $params)
    {
        if(!checkIsHasField($params,'shop_id')){
            $params['shop_id'] = getShopId();
        }
        if(!self::builder_query()->create($params)){
            self::error('添加失败');
        }
    }

    public static function info(array $params = []): array
    {
        if(!checkIsHasField($params,'is_shop_id')){
            $params['shop_id'] = getShopId();
        }
        return self::builder_query($params)->first()->toArray();
    }

    public static function edit(array $params)
    {
        if(!checkIsHasField($params,'shop_id')){
            $params['shop_id'] = getShopId();
        }
        if (self::builder_query(['goods_id'=>$params['goods_id']])->update(self::filterFields($params,new GoodsModel())) === false){
            self::error('修改失败');
        }
    }
}
